<?php
// 引用header.php文件
include 'header.php';
?>
    <style>
        /* Dashboard 页面特有样式 */

        /* Dashboard 页面表单样式 */
        .form-section {
            margin-bottom: 32px;
        }

        .form-section:last-child {
            margin-bottom: 0;
        }

        .form-section-title {
            font-size: 1.2rem;
            font-weight: 600;
            color: var(--gray-900);
            margin-bottom: 16px;
            padding-bottom: 8px;
            border-bottom: 1px solid var(--gray-200);
        }

        .form-grid {
            display: grid;
            gap: 20px;
        }

        .form-group {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }

        .form-label {
            font-weight: 600;
            color: var(--gray-700);
            font-size: 0.95rem;
        }

        .form-input,
        .form-textarea {
            padding: 12px 16px;
            border: 2px solid var(--gray-200);
            border-radius: var(--border-radius);
            font-size: 1rem;
            transition: all 0.2s ease;
            background: var(--white);
            width: 100%;
            max-width: 100%;
            box-sizing: border-box;
        }

        .form-input:focus,
        .form-textarea:focus {
            border-color: var(--primary-blue);
            outline: none;
            box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
        }

        .form-textarea {
            resize: vertical;
            min-height: 100px;
        }

        /* 链接管理 */
        .links-container {
            display: grid;
            gap: 20px;
        }

        .link-card {
            background: var(--white);
            border: 1px solid var(--gray-100);
            border-radius: 12px;
            padding: 0;
            transition: all 0.3s ease;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
            overflow: hidden;
            width: 100%;
            max-width: 100%;
        }

        .link-card:hover {
            border-color: var(--primary-blue);
            box-shadow: 0 12px 32px rgba(37, 99, 235, 0.18);
            transform: translateY(-3px);
        }

        .link-card:active {
            transform: translateY(-1px);
            box-shadow: 0 4px 16px rgba(37, 99, 235, 0.12);
        }

        .link-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            padding: 24px;
            margin-bottom: 0;
        }

        .link-info {
            flex: 1;
            min-width: 0;
            /* 防止文本溢出 */
        }

        .link-title {
            font-size: 1.2rem;
            font-weight: 600;
            color: var(--gray-900);
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            gap: 12px;
            line-height: 1.4;
        }

        .link-title i {
            font-size: 1.1rem;
            color: var(--primary-blue);
            width: 20px;
            text-align: center;
            transition: transform 0.2s ease;
        }

        .link-card:hover .link-title i {
            transform: scale(1.1);
        }

        .link-url {
            font-size: 0.9rem;
            color: var(--primary-blue);
            text-decoration: none;
            word-break: break-word;
            overflow-wrap: break-word;
            font-weight: 500;
            transition: color 0.2s ease;
            max-width: 100%;
        }

        .link-url:hover {
            color: var(--primary-blue-dark);
            text-decoration: underline;
        }

        .link-description {
            font-size: 0.95rem;
            color: var(--gray-600);
            margin-top: 10px;
            line-height: 1.5;
        }

        .link-stats {
            display: flex;
            align-items: center;
            gap: 16px;
            padding: 16px 24px;
            background: var(--gray-50);
            border-top: 1px solid var(--gray-100);
            margin: 0;
        }

        .link-clicks {
            font-size: 0.9rem;
            color: var(--gray-600);
            display: flex;
            align-items: center;
            gap: 8px;
            font-weight: 500;
        }

        .link-clicks i {
            color: var(--primary-blue);
            font-size: 0.85rem;
        }

        .link-actions {
            display: flex;
            gap: 8px;
            flex-shrink: 0;
        }

        .btn-sm {
            padding: 8px 16px;
            font-size: 0.85rem;
            border-radius: 8px;
            font-weight: 500;
            transition: all 0.2s ease;
            border: 1px solid transparent;
        }

        .btn-secondary {
            background: var(--gray-100);
            color: var(--gray-700);
            border-color: var(--gray-200);
        }

        .btn-secondary:hover {
            background: var(--gray-200);
            color: var(--gray-800);
            transform: translateY(-1px);
        }

        .btn-danger {
            background: #fee2e2;
            color: #dc2626;
            border-color: #fecaca;
        }

        .btn-danger:hover {
            background: #fecaca;
            color: #b91c1c;
            transform: translateY(-1px);
        }

        /* Ant Design 风格消息提示 */
        .ant-message {
            position: fixed;
            top: 24px;
            left: 50%;
            transform: translateX(-50%);
            z-index: 1100;
            pointer-events: none;
            width: 100%;
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 8px;
        }

        .ant-message-notice {
            background: var(--white);
            border-radius: 8px;
            box-shadow: 0 6px 16px 0 rgba(0, 0, 0, 0.08), 0 3px 6px -4px rgba(0, 0, 0, 0.12), 0 9px 28px 8px rgba(0, 0, 0, 0.05);
            display: flex;
            align-items: center;
            padding: 10px 16px;
            font-size: 14px;
            line-height: 1.5715;
            pointer-events: auto;
            position: relative;
            opacity: 0;
            transform: translateY(-100%);
            transition: all 0.3s cubic-bezier(0.78, 0.14, 0.15, 0.86);
            max-width: 90vw;
            word-break: break-word;
        }

        .ant-message-notice.show {
            opacity: 1;
            transform: translateY(0);
        }

        .ant-message-notice.hide {
            opacity: 0;
            transform: translateY(-100%);
            margin-top: -50px;
        }

        .ant-message-icon {
            margin-right: 8px;
            font-size: 16px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .ant-message-content {
            flex: 1;
        }

        .ant-message-close {
            margin-left: 12px;
            cursor: pointer;
            color: rgba(0, 0, 0, 0.45);
            font-size: 12px;
            transition: color 0.3s;
            display: flex;
            align-items: center;
        }

        .ant-message-close:hover {
            color: rgba(0, 0, 0, 0.75);
        }

        /* 不同类型的消息样式 */
        .ant-message-success .ant-message-icon {
            color: #52c41a;
        }

        .ant-message-error .ant-message-icon {
            color: #ff4d4f;
        }

        .ant-message-warning .ant-message-icon {
            color: #faad14;
        }

        .ant-message-info .ant-message-icon {
            color: #1890ff;
        }

        .ant-message-loading .ant-message-icon {
            color: #1890ff;
        }

        /* 加载动画 */
        .ant-message-loading .ant-message-icon {
            animation: ant-spin 1s infinite linear;
        }

        @keyframes ant-spin {
            to {
                transform: rotate(360deg);
            }
        }

        /* 模态框 */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            animation: fadeIn 0.2s ease;
        }

        .modal.show {
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .modal-content {
            background: var(--white);
            border-radius: var(--border-radius-lg);
            padding: 32px;
            width: 90%;
            max-width: 500px;
            max-height: 90vh;
            overflow-y: auto;
            box-shadow: var(--shadow-xl);
            animation: slideInUp 0.3s ease;
        }

        .modal-header {
            margin-bottom: 24px;
        }

        .modal-title {
            font-size: 1.5rem;
            font-weight: 700;
            color: var(--gray-900);
            margin: 0;
        }

        .modal-footer {
            display: flex;
            justify-content: flex-end;
            gap: 12px;
            margin-top: 24px;
            padding-top: 24px;
            border-top: 1px solid var(--gray-200);
        }

        /* 动画 */
        @keyframes fadeIn {
            from {
                opacity: 0;
            }

            to {
                opacity: 1;
            }
        }

        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        @keyframes slideInUp {
            from {
                opacity: 0;
                transform: translateY(20px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        /* 移动端优化 */
        @media (max-width: 768px) {
            .form-section {
                margin-bottom: 24px;
            }

            .form-section-title {
                font-size: 1.1rem;
                margin-bottom: 12px;
            }

            .form-group {
                gap: 6px;
            }

            .form-label {
                font-size: 0.9rem;
            }

            .form-input,
            .form-textarea {
                padding: 10px 14px;
                font-size: 0.95rem;
                width: 100%;
                max-width: 100%;
                box-sizing: border-box;
            }

            .form-textarea {
                min-height: 80px;
            }

            .links-container {
                gap: 16px;
            }

            .link-card {
                border-radius: 10px;
            }

            .link-header {
                flex-direction: column;
                gap: 16px;
                align-items: stretch;
                padding: 20px;
            }

            .link-info {
                order: 1;
            }

            .link-title {
                font-size: 1.1rem;
                gap: 10px;
            }

            .link-url {
                font-size: 0.9rem;
            }

            .link-description {
                font-size: 0.9rem;
                margin-top: 8px;
            }

            .link-actions {
                order: 2;
                display: flex;
                gap: 10px;
            }

            .link-actions .btn-sm {
                flex: 1;
                justify-content: center;
                font-size: 0.85rem;
                padding: 10px 16px;
                border-radius: 8px;
            }

            .link-stats {
                padding: 14px 20px;
            }

            .modal-content {
                width: 95%;
                margin: 16px;
                padding: 20px;
                border-radius: 12px;
                max-height: 90vh;
            }

            .modal-header {
                margin-bottom: 16px;
            }

            .modal-title {
                font-size: 1.3rem;
            }

            .modal-footer {
                margin-top: 16px;
                padding-top: 16px;
                flex-direction: row;
                gap: 8px;
            }

            .modal-footer .btn {
                flex: 1;
                justify-content: center;
            }

            .message {
                margin-bottom: 16px;
                padding: 12px 16px;
                font-size: 0.9rem;
            }

            .empty-state {
                padding: 32px 16px;
            }

            .empty-state i {
                font-size: 2.5rem;
                margin-bottom: 12px;
            }

            .empty-state h3 {
                font-size: 1.1rem;
                margin-bottom: 6px;
            }

            .empty-state p {
                font-size: 0.9rem;
                margin-bottom: 16px;
            }
        }

        /* 小屏手机优化 (≤480px) */
        @media (max-width: 480px) {
            .overview-stats {
                grid-template-columns: repeat(3, 1fr);
                gap: 8px;
            }

            .stat-card-large {
                padding: 12px;
                flex-direction: column;
                text-align: center;
                gap: 6px;
                align-items: center;
                min-height: 100px;
            }

            .stat-icon {
                width: 32px;
                height: 32px;
                font-size: 1rem;
                margin-right: 0;
                margin-bottom: 6px;
                flex-shrink: 0;
            }

            .stat-card-large .stat-number {
                font-size: 1.2rem;
                margin-bottom: 2px;
                line-height: 1.1;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
                max-width: 100%;
            }

            .stat-card-large .stat-label {
                font-size: 0.7rem;
                line-height: 1.2;
            }

            .form-section-title {
                font-size: 1rem;
            }

            .link-card {
                border-radius: 8px;
            }

            .link-header {
                padding: 16px;
            }

            .link-title {
                font-size: 1rem;
            }

            .link-actions .btn-sm {
                font-size: 0.8rem;
                padding: 8px 12px;
                border-radius: 6px;
            }

            .link-stats {
                padding: 12px 16px;
            }

            .modal-content {
                width: 98%;
                margin: 8px;
                padding: 16px;
            }

            .empty-state {
                padding: 24px 12px;
            }

            .empty-state i {
                font-size: 2rem;
            }
        }

        /* 加载状态 */
        .loading {
            opacity: 0.6;
            pointer-events: none;
        }

        .spinner {
            display: inline-block;
            width: 16px;
            height: 16px;
            border: 2px solid var(--gray-300);
            border-radius: 50%;
            border-top-color: var(--primary-blue);
            animation: spin 1s ease-in-out infinite;
        }

        @keyframes spin {
            to {
                transform: rotate(360deg);
            }
        }

        /* 空状态 */
        .empty-state {
            text-align: center;
            padding: 48px 24px;
            color: var(--gray-500);
        }

        .empty-state i {
            font-size: 3rem;
            margin-bottom: 16px;
            color: var(--gray-400);
        }

        .empty-state h3 {
            font-size: 1.25rem;
            font-weight: 600;
            margin-bottom: 8px;
            color: var(--gray-700);
        }

        .empty-state p {
            margin-bottom: 24px;
        }


        .form-actions {
            display: flex;
            justify-content: flex-end;
            gap: 12px;
            margin-top: 20px;
            padding-top: 16px;
            border-top: 1px solid var(--gray-200);
        }

        /* 概览页面样式 */
        .overview-stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 24px;
            margin-bottom: 32px;
        }

        @media (min-width: 768px) {
            .overview-stats {
                grid-template-columns: repeat(3, 1fr);
                gap: 20px;
                width: 100%;
            }
        }

        .stat-card-large {
            display: flex;
            align-items: center;
            padding: 24px;
            background: var(--white);
            border-radius: var(--border-radius-lg);
            border: 1px solid var(--gray-200);
            box-shadow: var(--shadow-sm);
            transition: all 0.2s ease;
            width: 100%;
            min-height: 120px;
        }

        .stat-card-large:hover {
            box-shadow: var(--shadow);
            transform: translateY(-1px);
        }

        /* 访问概览页面样式 */
        .visit-stats-overview {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 32px;
        }

        @media (min-width: 768px) {
            .visit-stats-overview {
                grid-template-columns: repeat(4, 1fr);
            }
        }

        .visit-records-section {
            background: var(--white);
            border-radius: var(--border-radius-lg);
            border: 1px solid var(--gray-200);
            overflow: hidden;
        }

        .section-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 20px 24px;
            border-bottom: 1px solid var(--gray-200);
            background: var(--gray-50);
        }

        .section-title {
            font-size: 18px;
            font-weight: 600;
            color: var(--gray-800);
            margin: 0;
        }

        .section-actions {
            display: flex;
            gap: 8px;
        }

        .visit-filters {
            display: flex;
            gap: 20px;
            padding: 20px 24px;
            border-bottom: 1px solid var(--gray-200);
            background: var(--white);
            flex-wrap: wrap;
        }

        .filter-group {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .filter-label {
            font-size: 14px;
            font-weight: 500;
            color: var(--gray-700);
            white-space: nowrap;
        }

        .filter-select,
        .filter-input {
            padding: 8px 12px;
            border: 1px solid var(--gray-300);
            border-radius: var(--border-radius);
            font-size: 14px;
            background: var(--white);
            color: var(--gray-800);
            min-width: 120px;
        }

        .filter-select:focus,
        .filter-input:focus {
            outline: none;
            border-color: var(--primary-blue);
            box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
        }

        .visit-table-container {
            overflow-x: auto;
        }

        .visit-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 14px;
        }

        .visit-table th,
        .visit-table td {
            padding: 12px 16px;
            text-align: left;
            border-bottom: 1px solid var(--gray-200);
        }

        .visit-table th {
            background: var(--gray-50);
            font-weight: 600;
            color: var(--gray-700);
            white-space: nowrap;
        }

        .visit-table td {
            color: var(--gray-800);
            vertical-align: middle;
        }

        .visit-table tr:hover {
            background: var(--gray-50);
        }

        .ip-address {
            font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
            font-size: 13px;
            color: var(--primary-blue);
            font-weight: 500;
        }

        .location-info {
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .location-flag {
            width: 16px;
            height: 12px;
            border-radius: 2px;
            background: var(--gray-200);
        }

        .duration-badge {
            display: inline-flex;
            align-items: center;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 500;
        }

        .duration-short {
            background: var(--error-red-light);
            color: var(--error-red);
        }

        .duration-medium {
            background: var(--warning-yellow-light);
            color: var(--warning-yellow);
        }

        .duration-long {
            background: var(--success-green-light);
            color: var(--success-green);
        }

        .device-info {
            display: flex;
            flex-direction: column;
            gap: 2px;
        }

        .device-type {
            font-size: 12px;
            color: var(--gray-600);
        }

        .device-os {
            font-size: 11px;
            color: var(--gray-500);
        }

        .browser-info {
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .browser-icon {
            width: 16px;
            height: 16px;
        }

        .status-badge {
            display: inline-flex;
            align-items: center;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 500;
        }

        .status-online {
            background: var(--success-green-light);
            color: var(--success-green);
        }

        .status-offline {
            background: var(--gray-200);
            color: var(--gray-600);
        }

        .pagination-container {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 20px 24px;
            border-top: 1px solid var(--gray-200);
            background: var(--gray-50);
        }

        .pagination-info {
            font-size: 14px;
            color: var(--gray-600);
        }

        .pagination {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .page-numbers {
            display: flex;
            gap: 4px;
        }

        .page-number {
            padding: 6px 12px;
            border: 1px solid var(--gray-300);
            border-radius: var(--border-radius);
            background: var(--white);
            color: var(--gray-700);
            text-decoration: none;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .page-number:hover {
            background: var(--gray-100);
            border-color: var(--gray-400);
        }

        .page-number.active {
            background: var(--primary-blue);
            border-color: var(--primary-blue);
            color: var(--white);
        }

        @media (max-width: 768px) {
            .visit-filters {
                flex-direction: column;
                gap: 12px;
            }

            .filter-group {
                flex-direction: column;
                align-items: flex-start;
                gap: 4px;
            }

            .filter-select,
            .filter-input {
                width: 100%;
                min-width: auto;
            }

            .pagination-container {
                flex-direction: column;
                gap: 12px;
                text-align: center;
            }

            .visit-table th,
            .visit-table td {
                padding: 8px 12px;
                font-size: 13px;
            }
        }

        .stat-icon {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 56px;
            height: 56px;
            background: linear-gradient(135deg, var(--primary-blue) 0%, var(--primary-blue-light) 100%);
            border-radius: var(--border-radius-lg);
            color: white;
            font-size: 1.5rem;
            margin-right: 20px;
        }

        .stat-info {
            flex: 1;
        }

        .stat-card-large .stat-number {
            font-size: 2.5rem;
            font-weight: 700;
            color: var(--gray-900);
            line-height: 1;
            margin-bottom: 4px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            max-width: 100%;
        }

        .stat-card-large .stat-label {
            font-size: 0.95rem;
            color: var(--gray-600);
            font-weight: 500;
        }

        .overview-section {
            margin-bottom: 32px;
        }

        .section-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .section-title {
            font-size: 1.25rem;
            font-weight: 600;
            color: var(--gray-900);
            margin: 0;
        }

        .section-action {
            color: var(--primary-blue);
            text-decoration: none;
            font-size: 0.9rem;
            font-weight: 500;
            transition: color 0.2s ease;
        }

        .section-action:hover {
            color: var(--primary-blue-dark);
        }

        .popular-links,
        .recent-links {
            background: var(--white);
            border-radius: var(--border-radius-lg);
            border: 1px solid var(--gray-200);
            overflow: hidden;
        }

        /* 热门链接样式 */
        .popular-link-item {
            display: flex;
            align-items: center;
            padding: 16px 20px;
            border-bottom: 1px solid var(--gray-100);
            transition: background-color 0.2s ease;
        }

        .popular-link-item:last-child {
            border-bottom: none;
        }

        .popular-link-item:hover {
            background-color: var(--gray-50);
        }


        .link-rank {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 32px;
            height: 32px;
            background: var(--primary-blue);
            color: white;
            border-radius: 50%;
            font-weight: 600;
            font-size: 0.9rem;
            margin-right: 16px;
        }

        .popular-link-item .link-icon {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 40px;
            height: 40px;
            background: var(--secondary-blue);
            border-radius: var(--border-radius);
            color: var(--primary-blue);
            margin-right: 16px;
            font-size: 1.1rem;
            flex-shrink: 0;
        }


        .link-details {
            flex: 1;
            min-width: 0;
        }


        .link-name,
        .link-title {
            font-weight: 600;
            color: var(--gray-900);
            margin-bottom: 4px;
            word-break: break-word;
            overflow-wrap: break-word;
            line-height: 1.4;
        }


        .link-domain {
            font-size: 0.85rem;
            color: var(--gray-500);
            word-break: break-word;
            overflow-wrap: break-word;
        }

        /* 概览页面的链接URL样式 */
        .popular-link-item .link-url {
            font-size: 0.85rem;
            color: var(--gray-500);
            word-break: break-word;
            overflow-wrap: break-word;
            max-width: 100%;
        }


        .link-clicks-count {
            text-align: right;
            margin-left: 16px;
            flex-shrink: 0;
        }

        .clicks-number {
            display: block;
            font-size: 1.5rem;
            font-weight: 700;
            color: var(--primary-blue);
            line-height: 1;
        }

        .clicks-label {
            font-size: 0.8rem;
            color: var(--gray-500);
        }

        /* 概览页面的链接统计样式 */
        .popular-link-item .link-stats {
            margin-left: 16px;
            display: flex;
            align-items: center;
            flex-shrink: 0;
        }

        .click-count {
            font-size: 0.9rem;
            color: var(--gray-600);
            font-weight: 500;
            white-space: nowrap;
        }

        .empty-state-small {
            text-align: center;
            padding: 40px 20px;
            color: var(--gray-500);
        }

        .empty-state-small i {
            font-size: 2rem;
            margin-bottom: 12px;
            color: var(--gray-400);
        }

        .empty-state-small p {
            margin: 0 0 16px 0;
            font-size: 0.95rem;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .overview-stats {
                gap: 12px;
                margin-bottom: 24px;
                grid-template-columns: repeat(3, 1fr);
            }

            .stat-card-large {
                padding: 16px;
                flex-direction: column;
                text-align: center;
                gap: 8px;
                align-items: center;
            }

            .stat-icon {
                width: 40px;
                height: 40px;
                font-size: 1.2rem;
                margin-right: 0;
                margin-bottom: 8px;
                flex-shrink: 0;
            }

            .stat-info {
                flex: 1;
                text-align: center;
            }

            .stat-card-large .stat-number {
                font-size: 1.4rem;
                margin-bottom: 4px;
                line-height: 1.2;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
                max-width: 100%;
            }

            .stat-card-large .stat-label {
                font-size: 0.75rem;
                line-height: 1.2;
            }

            .section-header {
                flex-direction: column;
                align-items: flex-start;
                gap: 8px;
            }

            .popular-link-item {
                padding: 12px 16px;
            }


            .link-rank {
                width: 28px;
                height: 28px;
                font-size: 0.8rem;
                margin-right: 12px;
            }

            .popular-link-item .link-icon {
                width: 36px;
                height: 36px;
                margin-right: 12px;
                font-size: 1rem;
            }


            .clicks-number {
                font-size: 1.3rem;
            }
        }
    </style>

<!-- Dashboard 主内容 -->
<div class="panel">
    <div class="panel-header">
        <h2 class="panel-title">网站概览</h2>
        <p class="panel-subtitle">查看您的网站统计数据和链接访问情况</p>
    </div>
    <div class="panel-content">
                    <!-- 统计卡片 -->
                    <div class="overview-stats">
                        <div class="stat-card-large">
                            <div class="stat-icon">
                                <i class="fas fa-link"></i>
                            </div>
                            <div class="stat-info">
                                <div class="stat-number">
                                    <?php
                                    $totalLinks = count($Data);
                                    if ($totalLinks >= 1000000) {
                                        echo round($totalLinks / 1000000, 1) . 'M';
                                    } elseif ($totalLinks >= 1000) {
                                        echo round($totalLinks / 1000, 1) . 'K';
                                    } else {
                                        echo $totalLinks;
                                    }
                                    ?>
                                </div>
                                <div class="stat-label">总链接数</div>
                            </div>
                        </div>
                        <div class="stat-card-large">
                            <div class="stat-icon">
                                <i class="fas fa-mouse-pointer"></i>
                            </div>
                            <div class="stat-info">
                                <div class="stat-number">
                                    <?php
                                    $totalClicks = 0;
                                    foreach ($Data as $link) {
                                        $totalClicks += intval($link['clicks'] ?? 0);
                                    }
                                    // 格式化大数字
                                    if ($totalClicks >= 1000000) {
                                        echo round($totalClicks / 1000000, 1) . 'M';
                                    } elseif ($totalClicks >= 1000) {
                                        echo round($totalClicks / 1000, 1) . 'K';
                                    } else {
                                        echo $totalClicks;
                                    }
                                    ?>
                                </div>
                                <div class="stat-label">总点击数</div>
                            </div>
                        </div>
                        <div class="stat-card-large">
                            <div class="stat-icon">
                                <i class="fas fa-chart-line"></i>
                            </div>
                            <div class="stat-info">
                                <div class="stat-number">
                                    <?php
                                    // 获取当天链接点击数
                                    $todayClicks = isset($visitStats['today_clicks']) ? $visitStats['today_clicks'] : 0;
                                    // 格式化大数字
                                    if ($todayClicks >= 1000000) {
                                        echo round($todayClicks / 1000000, 1) . 'M';
                                    } elseif ($todayClicks >= 1000) {
                                        echo round($todayClicks / 1000, 1) . 'K';
                                    } else {
                                        echo $todayClicks;
                                    }
                                    ?>
                                </div>
                                <div class="stat-label">当天点击</div>
                            </div>
                        </div>
                    </div>

                    <!-- 访问统计数据 -->
                    <div class="overview-section" style="margin-top: 32px;">
                        <div class="section-header">
                            <h3 class="section-title">
                                <i class="fas fa-chart-bar" style="margin-right: 8px; color: var(--primary-blue);"></i>
                                访问统计
                            </h3>
                        </div>
                        <?php
                        // $visitStats 已在 header.php 中获取
                        ?>
                        <div class="visit-charts-grid" style="margin-bottom: 24px;">
                            <!-- 柱状图：今日 vs 总体对比 -->
                            <div class="chart-container"
                                style="background: white; border-radius: 12px; padding: 24px; box-shadow: var(--shadow);">
                                <h4
                                    style="margin: 0 0 20px 0; font-size: 1.1rem; color: var(--gray-800); display: flex; align-items: center; gap: 8px;">
                                    <i class="fas fa-chart-bar" style="color: var(--primary-blue);"></i>
                                    访问量对比
                                </h4>
                                <div class="chart-wrapper" style="width: 100%; height: 300px; position: relative;">
                                    <canvas id="visitBarChart"></canvas>
                                </div>
                            </div>

                            <!-- 饼图：访客占比 -->
                            <div class="chart-container"
                                style="background: white; border-radius: 12px; padding: 24px; box-shadow: var(--shadow);">
                                <h4
                                    style="margin: 0 0 20px 0; font-size: 1.1rem; color: var(--gray-800); display: flex; align-items: center; gap: 8px;">
                                    <i class="fas fa-chart-pie" style="color: var(--primary-blue);"></i>
                                    访客分布
                                </h4>
                                <div class="chart-wrapper" style="width: 100%; height: 300px; position: relative;">
                                    <canvas id="visitPieChart"></canvas>
                                </div>
                            </div>
                        </div>

                        <style>
                            /* 响应式访问统计图表布局 */
                            .visit-charts-grid {
                                display: grid;
                                gap: 24px;
                                /* 默认两列布局，在更大屏幕上保持两列 */
                                grid-template-columns: repeat(2, 1fr);
                            }

                            /* 移动端：小于576px时显示单列 */
                            @media (max-width: 575px) {
                                .visit-charts-grid {
                                    grid-template-columns: 1fr;
                                }
                            }

                            /* 图表容器响应式优化 */
                            .chart-container {
                                width: 100%;
                                max-width: 100%;
                                overflow: hidden;
                            }

                            .chart-wrapper {
                                width: 100% !important;
                                max-width: 100%;
                                overflow: hidden;
                            }

                            /* 移动端图表优化 */
                            @media (max-width: 768px) {
                                .chart-container {
                                    padding: 16px !important;
                                }

                                .chart-container h4 {
                                    font-size: 1rem !important;
                                    margin-bottom: 16px !important;
                                }

                                .chart-wrapper {
                                    height: 250px !important;
                                }
                            }

                            /* 小屏手机端进一步优化 */
                            @media (max-width: 480px) {
                                .chart-container {
                                    padding: 12px !important;
                                    margin: 0 -4px;
                                }

                                .chart-container h4 {
                                    font-size: 0.95rem !important;
                                    gap: 6px !important;
                                }

                                .chart-wrapper {
                                    height: 220px !important;
                                }
                            }


                            /* 地区统计网格 - 响应式布局 */
                            .location-stats-grid {
                                display: grid;
                                gap: 12px;
                                grid-template-columns: 1fr;
                            }

                            @media (min-width: 480px) {
                                .location-stats-grid {
                                    grid-template-columns: repeat(2, 1fr);
                                }
                            }

                            @media (min-width: 768px) {
                                .location-stats-grid {
                                    grid-template-columns: repeat(3, 1fr);
                                }
                            }

                            @media (min-width: 1024px) {
                                .location-stats-grid {
                                    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
                                }
                            }
                        </style>

                        <!-- 数据卡片 -->
                        <style>
                            /* 访问统计卡片布局 - 电脑端一行四个 */
                            .visit-stats-cards {
                                display: grid;
                                gap: 20px;
                                margin-bottom: 32px;
                            }

                            /* 手机端：两行，每行两个 */
                            @media (max-width: 767px) {
                                .visit-stats-cards {
                                    grid-template-columns: repeat(2, 1fr);
                                    gap: 12px;
                                }
                            }

                            /* 电脑端：一行四个 */
                            @media (min-width: 768px) {
                                .visit-stats-cards {
                                    grid-template-columns: repeat(4, 1fr);
                                }
                            }
                        </style>
                        <div class="overview-stats visit-stats-cards">
                            <div class="stat-card-large"
                                style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white;">
                                <div class="stat-icon" style="background: rgba(255, 255, 255, 0.2);">
                                    <i class="fas fa-eye" style="color: white;"></i>
                                </div>
                                <div class="stat-info">
                                    <div class="stat-number" style="color: white;">
                                        <?php echo $visitStats['today_visits']; ?>
                                    </div>
                                    <div class="stat-label" style="color: rgba(255, 255, 255, 0.9);">今日访问</div>
                                </div>
                            </div>
                            <div class="stat-card-large"
                                style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); color: white;">
                                <div class="stat-icon" style="background: rgba(255, 255, 255, 0.2);">
                                    <i class="fas fa-users" style="color: white;"></i>
                                </div>
                                <div class="stat-info">
                                    <div class="stat-number" style="color: white;">
                                        <?php echo $visitStats['today_ips']; ?>
                                    </div>
                                    <div class="stat-label" style="color: rgba(255, 255, 255, 0.9);">今日访客</div>
                                </div>
                            </div>
                            <div class="stat-card-large"
                                style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); color: white;">
                                <div class="stat-icon" style="background: rgba(255, 255, 255, 0.2);">
                                    <i class="fas fa-globe" style="color: white;"></i>
                                </div>
                                <div class="stat-info">
                                    <div class="stat-number" style="color: white;">
                                        <?php echo number_format($visitStats['total_visits']); ?>
                                    </div>
                                    <div class="stat-label" style="color: rgba(255, 255, 255, 0.9);">总访问量</div>
                                </div>
                            </div>
                            <div class="stat-card-large"
                                style="background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%); color: white;">
                                <div class="stat-icon" style="background: rgba(255, 255, 255, 0.2);">
                                    <i class="fas fa-user-friends" style="color: white;"></i>
                                </div>
                                <div class="stat-info">
                                    <div class="stat-number" style="color: white;">
                                        <?php echo number_format($visitStats['total_ips']); ?>
                                    </div>
                                    <div class="stat-label" style="color: rgba(255, 255, 255, 0.9);">总访客数</div>
                                </div>
                            </div>
                        </div>

                        <!-- 初始化图表的脚本 -->
                        <script>
                            // 页面加载完成后初始化图表
                            document.addEventListener('DOMContentLoaded', function () {
                                initVisitCharts();
                            });

                            function initVisitCharts() {
                                // 访问统计数据
                                const visitData = {
                                    todayVisits: <?php echo $visitStats['today_visits']; ?>,
                                    todayIps: <?php echo $visitStats['today_ips']; ?>,
                                    totalVisits: <?php echo $visitStats['total_visits']; ?>,
                                    totalIps: <?php echo $visitStats['total_ips']; ?>
                                };

                                // 柱状图：今日 vs 总体对比
                                const barCtx = document.getElementById('visitBarChart');
                                if (barCtx) {
                                    new Chart(barCtx, {
                                        type: 'bar',
                                        data: {
                                            labels: ['今日访问', '总访问量', '今日访客', '总访客数'],
                                            datasets: [{
                                                label: '数量',
                                                data: [
                                                    visitData.todayVisits,
                                                    visitData.totalVisits,
                                                    visitData.todayIps,
                                                    visitData.totalIps
                                                ],
                                                backgroundColor: [
                                                    'rgba(37, 99, 235, 0.8)',    // 主蓝色 #2563eb
                                                    'rgba(59, 130, 246, 0.8)',   // 亮蓝色 #3b82f6
                                                    'rgba(96, 165, 250, 0.8)',   // 天蓝色 #60a5fa
                                                    'rgba(147, 197, 253, 0.8)'   // 浅蓝色 #93c5fd
                                                ],
                                                borderColor: [
                                                    'rgb(37, 99, 235)',
                                                    'rgb(59, 130, 246)',
                                                    'rgb(96, 165, 250)',
                                                    'rgb(147, 197, 253)'
                                                ],
                                                borderWidth: 2,
                                                borderRadius: 8,
                                                borderSkipped: false
                                            }]
                                        },
                                        options: {
                                            responsive: true,
                                            maintainAspectRatio: false,
                                            plugins: {
                                                legend: {
                                                    display: false
                                                },
                                                tooltip: {
                                                    backgroundColor: 'rgba(0, 0, 0, 0.8)',
                                                    padding: 12,
                                                    cornerRadius: 8,
                                                    titleFont: {
                                                        size: window.innerWidth < 768 ? 12 : 14
                                                    },
                                                    bodyFont: {
                                                        size: window.innerWidth < 768 ? 11 : 13
                                                    }
                                                }
                                            },
                                            scales: {
                                                y: {
                                                    beginAtZero: true,
                                                    ticks: {
                                                        font: {
                                                            size: window.innerWidth < 768 ? 10 : 12
                                                        }
                                                    },
                                                    grid: {
                                                        color: 'rgba(0, 0, 0, 0.05)'
                                                    }
                                                },
                                                x: {
                                                    ticks: {
                                                        font: {
                                                            size: window.innerWidth < 768 ? 10 : 12
                                                        },
                                                        maxRotation: window.innerWidth < 768 ? 30 : 45,
                                                        minRotation: 0
                                                    },
                                                    grid: {
                                                        display: false
                                                    }
                                                }
                                            }
                                        }
                                    });
                                }

                                // 饼图：访客占比
                                const pieCtx = document.getElementById('visitPieChart');
                                if (pieCtx) {
                                    new Chart(pieCtx, {
                                        type: 'doughnut',
                                        data: {
                                            labels: ['今日访问', '今日访客', '历史访问', '历史访客'],
                                            datasets: [{
                                                data: [
                                                    visitData.todayVisits,
                                                    visitData.todayIps,
                                                    Math.max(0, visitData.totalVisits - visitData.todayVisits),
                                                    Math.max(0, visitData.totalIps - visitData.todayIps)
                                                ],
                                                backgroundColor: [
                                                    'rgba(37, 99, 235, 0.8)',    // 主蓝色
                                                    'rgba(59, 130, 246, 0.8)',   // 亮蓝色
                                                    'rgba(96, 165, 250, 0.8)',   // 天蓝色
                                                    'rgba(147, 197, 253, 0.8)'   // 浅蓝色
                                                ],
                                                borderColor: [
                                                    'rgb(37, 99, 235)',
                                                    'rgb(59, 130, 246)',
                                                    'rgb(96, 165, 250)',
                                                    'rgb(147, 197, 253)'
                                                ],
                                                borderWidth: 2
                                            }]
                                        },
                                        options: {
                                            responsive: true,
                                            maintainAspectRatio: false,
                                            plugins: {
                                                legend: {
                                                    position: window.innerWidth > 768 ? 'right' : 'bottom',
                                                    labels: {
                                                        padding: window.innerWidth > 768 ? 10 : 8,
                                                        font: {
                                                            size: window.innerWidth > 768 ? 11 : 9
                                                        },
                                                        usePointStyle: true,
                                                        pointStyle: 'circle',
                                                        boxWidth: window.innerWidth > 768 ? 12 : 10
                                                    }
                                                },
                                                tooltip: {
                                                    backgroundColor: 'rgba(0, 0, 0, 0.8)',
                                                    padding: 12,
                                                    cornerRadius: 8,
                                                    titleFont: {
                                                        size: window.innerWidth < 768 ? 12 : 14
                                                    },
                                                    bodyFont: {
                                                        size: window.innerWidth < 768 ? 11 : 13
                                                    },
                                                    callbacks: {
                                                        label: function (context) {
                                                            const label = context.label || '';
                                                            const value = context.parsed || 0;
                                                            const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                                            const percentage = ((value / total) * 100).toFixed(1);
                                                            return label + ': ' + value.toLocaleString() + ' (' + percentage + '%)';
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    });
                                }
                            }
                        </script>
                    </div>

                    <!-- 访客地理位置分布 -->
                    <div class="overview-section" style="margin-top: 32px;">
                        <div class="section-header">
                            <h3 class="section-title">
                                <i class="fas fa-map-marked-alt"
                                    style="margin-right: 8px; color: var(--primary-blue);"></i>
                                访客地理分布
                            </h3>
                            <button class="btn btn-secondary btn-sm" onclick="refreshVisitorLocations()"
                                id="refreshLocationBtn">
                                <i class="fas fa-sync-alt"></i>
                                刷新位置
                            </button>
                        </div>
                        <!-- 地理分布图表 -->
                        <div class="location-charts-grid" style="margin-bottom: 24px;">
                            <!-- 柱状图：地区访问量 -->
                            <div class="chart-container"
                                style="background: white; border-radius: 12px; padding: 24px; box-shadow: var(--shadow);">
                                <h4
                                    style="margin: 0 0 20px 0; font-size: 1.1rem; color: var(--gray-800); display: flex; align-items: center; gap: 8px;">
                                    <i class="fas fa-chart-bar" style="color: var(--primary-blue);"></i>
                                    地区访问量排行
                                </h4>
                                <div id="locationBarChartContainer" class="chart-wrapper"
                                    style="width: 100%; height: 300px; position: relative;">
                                    <canvas id="locationBarChart"></canvas>
                                </div>
                            </div>

                            <!-- 饼图：地区访问占比 -->
                            <div class="chart-container"
                                style="background: white; border-radius: 12px; padding: 24px; box-shadow: var(--shadow);">
                                <h4
                                    style="margin: 0 0 20px 0; font-size: 1.1rem; color: var(--gray-800); display: flex; align-items: center; gap: 8px;">
                                    <i class="fas fa-chart-pie" style="color: var(--primary-blue);"></i>
                                    地区访问占比
                                </h4>
                                <div id="locationPieChartContainer" class="chart-wrapper"
                                    style="width: 100%; height: 300px; position: relative;">
                                    <canvas id="locationPieChart"></canvas>
                                </div>
                            </div>
                        </div>

                        <style>
                            /* 响应式图表布局 */
                            .location-charts-grid {
                                display: grid;
                                gap: 24px;
                                /* 默认单列布局（移动端） */
                                grid-template-columns: 1fr;
                            }

                            /* 桌面端：大于768px时显示两列 */
                            @media (min-width: 768px) {
                                .location-charts-grid {
                                    grid-template-columns: repeat(2, 1fr);
                                }
                            }
                        </style>

                        <!-- 访客位置详情 -->
                        <div style="background: white; border-radius: 12px; padding: 24px; box-shadow: var(--shadow);">
                            <div id="visitorLocationsContainer">
                                <div style="text-align: center; padding: 40px; color: var(--gray-500);">
                                    <i class="fas fa-spinner fa-spin"
                                        style="font-size: 2rem; margin-bottom: 12px; color: var(--primary-blue);"></i>
                                    <p style="margin: 0;">正在加载访客位置信息...</p>
                                </div>
                            </div>
                        </div>

                        <script>
                            // 直接从文件读取访客位置信息
                            async function loadVisitorLocations() {
                                const container = document.getElementById('visitorLocationsContainer');

                                try {
                                    // 读取IP位置文件
                                    const locationResponse = await fetch('../ip_locations.json?t=' + Date.now());

                                    let locationData = { ip_locations: {}, location_stats: {} };
                                    if (locationResponse.ok) {
                                        locationData = await locationResponse.json();
                                    }
                                    
                                    const ipLocations = locationData.ip_locations || {};
                                    const locationStats = locationData.location_stats || {};

                                    // 读取今日访问IP
                                    const statsResponse = await fetch('../visit_stats.json?t=' + Date.now());
                                    if (!statsResponse.ok) {
                                        throw new Error('无法读取访问统计数据');
                                    }

                                    const statsData = await statsResponse.json();
                                    const todayIPs = statsData.today_ips || [];

                                    if (!todayIPs || todayIPs.length === 0) {
                                        container.innerHTML = `
                                        <div style="text-align: center; padding: 40px; color: var(--gray-500);">
                                            <i class="fas fa-map-marker-alt" style="font-size: 2rem; margin-bottom: 12px; color: var(--gray-400);"></i>
                                            <p style="margin: 0;">今日暂无访客数据</p>
                                        </div>
                                    `;
                                        // 初始化图表（显示无数据提示）
                                        initLocationCharts(locationStats);
                                        return;
                                    }

                                    // 获取今日IP的位置信息
                                    const todayLocations = [];
                                    todayIPs.slice(-20).reverse().forEach(ip => {
                                        if (ipLocations[ip]) {
                                            todayLocations.push({
                                                ip: ip,
                                                ...ipLocations[ip]
                                            });
                                        }
                                    });

                                    if (todayLocations.length === 0) {
                                        container.innerHTML = `
                                        <div style="text-align: center; padding: 40px; color: var(--gray-500);">
                                            <i class="fas fa-clock" style="font-size: 2rem; margin-bottom: 12px; color: var(--gray-400);"></i>
                                            <p style="margin: 0;">位置信息正在加载中，请稍候刷新...</p>
                                        </div>
                                    `;
                                        // 初始化图表（显示无数据提示）
                                        initLocationCharts(locationStats);
                                        return;
                                    }

                                    // 不显示访客位置卡片，直接设置空的HTML
                                    let html = '';

                                    container.innerHTML = html;

                                    // 初始化地区访问图表
                                    initLocationCharts(locationStats);

                                } catch (error) {
                                    console.error('加载访客位置失败:', error);
                                    container.innerHTML = '';
                                    // 即使出错也要初始化图表（显示无数据提示）
                                    initLocationCharts(null);
                                }
                            }

                            // 保存图表实例
                            let barChartInstance = null;
                            let pieChartInstance = null;

                            // 初始化地区访问图表
                            function initLocationCharts(locationStats) {
                                const barContainer = document.getElementById('locationBarChartContainer');
                                const pieContainer = document.getElementById('locationPieChartContainer');

                                // 销毁旧的图表实例
                                if (barChartInstance) {
                                    barChartInstance.destroy();
                                    barChartInstance = null;
                                }
                                if (pieChartInstance) {
                                    pieChartInstance.destroy();
                                    pieChartInstance = null;
                                }

                                // 无数据时显示提示
                                if (!locationStats || Object.keys(locationStats).length === 0) {
                                    const emptyMessage = `
                                    <div style="text-align: center; padding: 60px 20px; color: var(--gray-500);">
                                        <i class="fas fa-chart-line" style="font-size: 2.5rem; margin-bottom: 12px; color: var(--gray-400);"></i>
                                        <p style="margin: 0; font-size: 0.95rem;">暂无地区访问数据</p>
                                        <p style="margin: 8px 0 0 0; font-size: 0.85rem; color: var(--gray-400);">访客访问后会自动统计</p>
                                    </div>
                                `;
                                    if (barContainer) barContainer.innerHTML = emptyMessage;
                                    if (pieContainer) pieContainer.innerHTML = emptyMessage;
                                    return;
                                }

                                // 按访问次数排序，取前10名
                                const sortedStats = Object.entries(locationStats)
                                    .sort((a, b) => b[1].count - a[1].count)
                                    .slice(0, 10);

                                const labels = sortedStats.map(([key, stat]) =>
                                    stat.display_name || key.split('-').filter(x => x).join(' ')
                                );
                                const counts = sortedStats.map(([key, stat]) => stat.count);

                                // 柱状图：地区访问量排行
                                const barCtx = document.getElementById('locationBarChart');
                                if (barCtx) {
                                    barChartInstance = new Chart(barCtx, {
                                        type: 'bar',
                                        data: {
                                            labels: labels,
                                            datasets: [{
                                                label: '访问次数',
                                                data: counts,
                                                backgroundColor: 'rgba(99, 102, 241, 0.8)',
                                                borderColor: 'rgb(99, 102, 241)',
                                                borderWidth: 1
                                            }]
                                        },
                                        options: {
                                            responsive: true,
                                            maintainAspectRatio: false,
                                            plugins: {
                                                legend: {
                                                    display: false
                                                },
                                                tooltip: {
                                                    backgroundColor: 'rgba(0, 0, 0, 0.8)',
                                                    padding: window.innerWidth < 768 ? 8 : 12,
                                                    cornerRadius: 8,
                                                    titleFont: {
                                                        size: window.innerWidth < 768 ? 11 : 13
                                                    },
                                                    bodyFont: {
                                                        size: window.innerWidth < 768 ? 10 : 12
                                                    },
                                                    callbacks: {
                                                        afterLabel: function (context) {
                                                            const index = context.dataIndex;
                                                            const stat = sortedStats[index][1];
                                                            return `独立IP: ${stat.ips.length}`;
                                                        }
                                                    }
                                                }
                                            },
                                            scales: {
                                                y: {
                                                    beginAtZero: true,
                                                    ticks: {
                                                        precision: 0,
                                                        font: {
                                                            size: window.innerWidth < 768 ? 9 : 11
                                                        }
                                                    },
                                                    grid: {
                                                        color: 'rgba(0, 0, 0, 0.05)'
                                                    }
                                                },
                                                x: {
                                                    ticks: {
                                                        autoSkip: window.innerWidth < 768,
                                                        maxRotation: window.innerWidth < 768 ? 45 : 45,
                                                        minRotation: window.innerWidth < 768 ? 30 : 0,
                                                        font: {
                                                            size: window.innerWidth < 768 ? 9 : 11
                                                        }
                                                    },
                                                    grid: {
                                                        display: false
                                                    }
                                                }
                                            }
                                        }
                                    });
                                }

                                // 饼图：地区访问占比
                                const pieCtx = document.getElementById('locationPieChart');
                                if (pieCtx) {
                                    // 生成渐变色
                                    const colors = [
                                        'rgba(99, 102, 241, 0.8)',   // 蓝紫色
                                        'rgba(139, 92, 246, 0.8)',   // 紫色
                                        'rgba(236, 72, 153, 0.8)',   // 粉红色
                                        'rgba(244, 63, 94, 0.8)',    // 红色
                                        'rgba(251, 146, 60, 0.8)',   // 橙色
                                        'rgba(34, 197, 94, 0.8)',    // 绿色
                                        'rgba(14, 165, 233, 0.8)',   // 天蓝色
                                        'rgba(168, 85, 247, 0.8)',   // 紫罗兰色
                                        'rgba(236, 252, 203, 0.8)',  // 黄绿色
                                        'rgba(147, 197, 253, 0.8)'   // 浅蓝色
                                    ];

                                    pieChartInstance = new Chart(pieCtx, {
                                        type: 'pie',
                                        data: {
                                            labels: labels,
                                            datasets: [{
                                                data: counts,
                                                backgroundColor: colors,
                                                borderWidth: 2,
                                                borderColor: '#fff'
                                            }]
                                        },
                                        options: {
                                            responsive: true,
                                            maintainAspectRatio: false,
                                            plugins: {
                                                legend: {
                                                    position: window.innerWidth < 768 ? 'bottom' : 'right',
                                                    labels: {
                                                        boxWidth: window.innerWidth < 768 ? 10 : 12,
                                                        padding: window.innerWidth < 768 ? 6 : 10,
                                                        font: {
                                                            size: window.innerWidth < 768 ? 9 : 11
                                                        },
                                                        usePointStyle: true,
                                                        pointStyle: 'circle'
                                                    }
                                                },
                                                tooltip: {
                                                    backgroundColor: 'rgba(0, 0, 0, 0.8)',
                                                    padding: window.innerWidth < 768 ? 8 : 12,
                                                    cornerRadius: 8,
                                                    titleFont: {
                                                        size: window.innerWidth < 768 ? 11 : 13
                                                    },
                                                    bodyFont: {
                                                        size: window.innerWidth < 768 ? 10 : 12
                                                    },
                                                    callbacks: {
                                                        label: function (context) {
                                                            const label = context.label || '';
                                                            const value = context.parsed || 0;
                                                            const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                                            const percentage = ((value / total) * 100).toFixed(1);
                                                            const index = context.dataIndex;
                                                            const stat = sortedStats[index][1];
                                                            return [
                                                                `${label}: ${value}次`,
                                                                `占比: ${percentage}%`,
                                                                `独立IP: ${stat.ips.length}`
                                                            ];
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    });
                                }
                            }

                            function refreshVisitorLocations() {
                                const btn = document.getElementById('refreshLocationBtn');
                                const icon = btn.querySelector('i');

                                // 添加旋转动画
                                icon.classList.add('fa-spin');
                                btn.disabled = true;

                                loadVisitorLocations().finally(() => {
                                    setTimeout(() => {
                                        icon.classList.remove('fa-spin');
                                        btn.disabled = false;
                                    }, 500);
                                });
                            }

                            // 显示通知消息
                            function showNotification(message, type = 'info') {
                                // 创建通知元素
                                const notification = document.createElement('div');
                                notification.style.cssText = `
                                position: fixed;
                                top: 20px;
                                right: 20px;
                                padding: 12px 20px;
                                border-radius: 8px;
                                color: white;
                                font-size: 0.9rem;
                                z-index: 10000;
                                box-shadow: 0 4px 12px rgba(0,0,0,0.15);
                                transform: translateX(100%);
                                transition: transform 0.3s ease;
                                max-width: 300px;
                            `;

                                // 设置颜色
                                switch (type) {
                                    case 'success':
                                        notification.style.background = 'var(--success-green)';
                                        break;
                                    case 'error':
                                        notification.style.background = 'var(--error-red)';
                                        break;
                                    default:
                                        notification.style.background = 'var(--primary-blue)';
                                }

                                notification.textContent = message;
                                document.body.appendChild(notification);

                                // 显示动画
                                setTimeout(() => {
                                    notification.style.transform = 'translateX(0)';
                                }, 100);

                                // 自动隐藏
                                setTimeout(() => {
                                    notification.style.transform = 'translateX(100%)';
                                    setTimeout(() => {
                                        document.body.removeChild(notification);
                                    }, 300);
                                }, 3000);
                            }

                            // 页面加载时自动加载访客位置
                            document.addEventListener('DOMContentLoaded', function () {
                                // 延迟加载，避免阻塞主要内容
                                setTimeout(() => {
                                    loadVisitorLocations();
                                }, 800);

                                // 窗口大小改变时，重新渲染图表以适应新尺寸
                                let resizeTimer;
                                window.addEventListener('resize', function () {
                                    clearTimeout(resizeTimer);
                                    resizeTimer = setTimeout(() => {
                                        // 地区图表
                                        if (barChartInstance) barChartInstance.resize();
                                        if (pieChartInstance) pieChartInstance.resize();

                                        // 访问统计图表（如果存在的话）
                                        const visitBarChart = Chart.getChart('visitBarChart');
                                        const visitPieChart = Chart.getChart('visitPieChart');
                                        if (visitBarChart) visitBarChart.resize();
                                        if (visitPieChart) visitPieChart.resize();
                                    }, 250);
                                });
                            });
                        </script>
                    </div>

                    <!-- 热门链接 -->
                    <div class="overview-section">
                        <div class="section-header">
                            <h3 class="section-title">热门链接</h3>
                            <a href="#links-management" class="section-action" onclick="switchTab('links-management')">
                                查看全部 <i class="fas fa-arrow-right"></i>
                            </a>
                        </div>
                        <div class="popular-links">
                            <?php if (empty($Data)): ?>
                                <div class="empty-state-small">
                                    <i class="fas fa-link"></i>
                                    <p>暂无链接数据</p>
                                    <button class="btn btn-primary btn-sm" onclick="switchTab('links-management')">
                                        添加链接
                                    </button>
                                </div>
                            <?php else: ?>
                                <?php
                                // 按点击数排序链接
                                $sortedLinks = $Data;
                                usort($sortedLinks, function ($a, $b) {
                                    return intval($b['clicks'] ?? 0) - intval($a['clicks'] ?? 0);
                                });
                                // 只显示前5个
                                $topLinks = array_slice($sortedLinks, 0, 5);
                                ?>
                                <?php foreach ($topLinks as $index => $link): ?>
                                    <div class="popular-link-item">
                                        <div class="link-rank"><?php echo $index + 1; ?></div>
                                        <div class="link-icon">
                                            <i class="<?php echo htmlspecialchars($link['icon'] ?? 'fas fa-link'); ?>"></i>
                                        </div>
                                        <div class="link-details">
                                            <div class="link-name"><?php echo htmlspecialchars($link['title']); ?></div>
                                            <div class="link-domain">
                                                <?php
                                                $domain = parse_url($link['url'], PHP_URL_HOST);
                                                echo htmlspecialchars($domain ?: $link['url']);
                                                ?>
                                            </div>
                                        </div>
                                        <div class="link-clicks-count">
                                            <span class="clicks-number"><?php echo intval($link['clicks'] ?? 0); ?></span>
                                            <span class="clicks-label">点击</span>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                    </div>

    </div>
</div>


    <script>
        // DOM 加载完成后初始化
        document.addEventListener('DOMContentLoaded', function () {
            // 显示PHP消息（如果有）
            <?php if ($message): ?>
                const messageType = '<?php echo strpos(strtolower($message), "成功") !== false ? "success" : "error"; ?>';
                const messageContent = <?php echo json_encode($message); ?>;
                showMessage(messageContent, messageType);
            <?php endif; ?>
        });




        // Ant Design 风格消息提示系统
        const AntMessage = {
            container: null,

            init() {
                this.container = document.getElementById('ant-message');
                if (!this.container) {
                    this.container = document.createElement('div');
                    this.container.className = 'ant-message';
                    this.container.id = 'ant-message';
                    document.body.appendChild(this.container);
                }
            },

            show(content, type = 'info', duration = 3) {
                if (!this.container) this.init();

                const icons = {
                    success: 'fas fa-check-circle',
                    error: 'fas fa-times-circle',
                    warning: 'fas fa-exclamation-triangle',
                    info: 'fas fa-info-circle',
                    loading: 'fas fa-spinner'
                };

                const notice = document.createElement('div');
                notice.className = `ant-message-notice ant-message-${type}`;

                notice.innerHTML = `
                    <span class="ant-message-icon">
                        <i class="${icons[type] || icons.info}"></i>
                    </span>
                    <span class="ant-message-content">${content}</span>
                    <span class="ant-message-close">
                        <i class="fas fa-times"></i>
                    </span>
                `;

                // 添加关闭按钮事件
                const closeBtn = notice.querySelector('.ant-message-close');
                closeBtn.addEventListener('click', () => {
                    this.hide(notice);
                });

                // 添加到容器
                this.container.appendChild(notice);

                // 显示动画
                setTimeout(() => {
                    notice.classList.add('show');
                }, 10);

                // 自动隐藏
                if (duration > 0) {
                    setTimeout(() => {
                        this.hide(notice);
                    }, duration * 1000);
                }

                return notice;
            },

            hide(notice) {
                if (!notice || !notice.parentNode) return;

                notice.classList.add('hide');
                setTimeout(() => {
                    if (notice.parentNode) {
                        notice.parentNode.removeChild(notice);
                    }
                }, 300);
            },

            success(content, duration = 3) {
                return this.show(content, 'success', duration);
            },

            error(content, duration = 4) {
                return this.show(content, 'error', duration);
            },

            warning(content, duration = 3) {
                return this.show(content, 'warning', duration);
            },

            info(content, duration = 3) {
                return this.show(content, 'info', duration);
            },

            loading(content, duration = 0) {
                return this.show(content, 'loading', duration);
            }
        };

        // 兼容旧的showMessage函数
        function showMessage(message, type = 'success') {
            AntMessage[type](message);
        }

        // 处理网站配置表单提交
        async function handleSiteConfigSubmit(e) {
            e.preventDefault();

            const submitButton = e.target.querySelector('button[type="submit"]');
            const originalText = submitButton.innerHTML;

            // 显示加载状态
            submitButton.innerHTML = '<span class="spinner"></span> 保存中...';
            submitButton.disabled = true;

            const formData = new FormData(e.target);
            const data = {
                site_title: formData.get('site_title'),
                site_docs: formData.get('site_docs'),
                site_token: formData.get('site_token')
            };

            const result = await apiRequest('updateSiteConfig', data);

            // 恢复按钮状态
            submitButton.innerHTML = originalText;
            submitButton.disabled = false;

            if (result.status === 'success') {
                showMessage(result.message, 'success');

                // 如果密钥被修改，重定向到登录页面
                if (result.data && result.data.redirect) {
                    setTimeout(() => {
                        window.location.href = result.data.redirect;
                    }, 1500);
                }
            } else {
                showMessage(result.message, 'error');
            }
        }

        // 处理添加链接表单提交
        async function handleAddLinkSubmit(e) {
            e.preventDefault();

            const submitButton = e.target.querySelector('button[type="submit"]');
            const originalText = submitButton.innerHTML;

            // 显示加载状态
            submitButton.innerHTML = '<span class="spinner"></span> 添加中...';
            submitButton.disabled = true;

            const formData = new FormData(e.target);
            const data = {
                title: formData.get('link_title'),
                url: formData.get('link_url'),
                description: formData.get('link_desc'),
                icon: formData.get('link_icon')
            };

            const result = await apiRequest('addLink', data);

            // 恢复按钮状态
            submitButton.innerHTML = originalText;
            submitButton.disabled = false;

            if (result.status === 'success') {
                showMessage(result.message, 'success');

                // 重置表单并关闭弹窗
                closeAddModal();

                // 更新链接数据和显示
                linksData = [...linksData, result.data.link];
                updateLinksDisplay();
                updateStats();

                // 切换到链接管理页面
                setTimeout(() => {
                    switchTab('links-management');
                }, 1000);
            } else {
                showMessage(result.message, 'error');
            }
        }

        // 处理编辑链接表单提交
        async function handleEditLinkSubmit(e) {
            e.preventDefault();

            const submitButton = e.target.querySelector('button[type="submit"]');
            const originalText = submitButton.innerHTML;

            // 显示加载状态
            submitButton.innerHTML = '<span class="spinner"></span> 保存中...';
            submitButton.disabled = true;

            const formData = new FormData(e.target);
            const data = {
                index: parseInt(formData.get('link_index')),
                title: formData.get('link_title'),
                url: formData.get('link_url'),
                description: formData.get('link_desc'),
                icon: formData.get('link_icon')
            };

            const result = await apiRequest('updateLink', data);

            // 恢复按钮状态
            submitButton.innerHTML = originalText;
            submitButton.disabled = false;

            if (result.status === 'success') {
                showMessage(result.message, 'success');

                // 更新链接数据和显示
                linksData[data.index] = result.data.link;
                updateLinksDisplay();

                // 关闭模态框
                closeModal();
            } else {
                showMessage(result.message, 'error');
            }
        }

        // 编辑链接
        function editLink(index) {
            const link = linksData[index];
            if (!link) return;

            // 填充表单数据
            document.getElementById('edit_link_index').value = index;
            document.getElementById('edit_link_title').value = link.title || '';
            document.getElementById('edit_link_url').value = link.url || '';
            document.getElementById('edit_link_desc').value = link.description || '';
            document.getElementById('edit_link_icon').value = link.icon || 'fas fa-link';

            // 显示模态框
            document.getElementById('edit-modal').classList.add('show');
        }

        // 删除链接
        async function deleteLink(index) {
            const link = linksData[index];
            if (!link) return;

            if (!confirm(`确定要删除链接 "${link.title}" 吗？此操作不可撤销。`)) {
                return;
            }

            const result = await apiRequest('deleteLink', { index });

            if (result.status === 'success') {
                showMessage(result.message, 'success');

                // 更新链接数据和显示
                linksData.splice(index, 1);
                updateLinksDisplay();
                updateStats();
            } else {
                showMessage(result.message, 'error');
            }
        }

        // 更新链接显示
        function updateLinksDisplay() {
            const container = document.getElementById('links-container');

            if (linksData.length === 0) {
                container.innerHTML = `
                    <div class="empty-state">
                        <i class="fas fa-link"></i>
                        <h3>暂无链接</h3>
                        <p>您还没有添加任何导航链接</p>
                        <button class="btn btn-primary" onclick="switchTab('add-link')">
                            <i class="fas fa-plus"></i>
                            添加第一个链接
                        </button>
                    </div>
                `;
            } else {
                container.innerHTML = linksData.map((link, index) => `
                    <div class="link-card" data-index="${index}">
                        <div class="link-header">
                            <div class="link-info">
                                <div class="link-title">
                                    <i class="${link.icon || 'fas fa-link'}"></i>
                                    ${escapeHtml(link.title)}
                                </div>
                                <a href="${escapeHtml(link.url)}" target="_blank" class="link-url">
                                    ${escapeHtml(link.url)}
                                </a>
                                ${link.description ? `
                                    <div class="link-description">
                                        ${escapeHtml(link.description)}
                                    </div>
                                ` : ''}
                            </div>
                            <div class="link-actions">
                                <button class="btn btn-sm btn-secondary" onclick="editLink(${index})">
                                    <i class="fas fa-edit"></i>
                                    编辑
                                </button>
                                <button class="btn btn-sm btn-danger" onclick="deleteLink(${index})">
                                    <i class="fas fa-trash"></i>
                                    删除
                                </button>
                            </div>
                        </div>
                        <div class="link-stats">
                            <span class="link-clicks">
                                <i class="fas fa-mouse-pointer"></i>
                                点击次数: ${link.clicks || 0}
                            </span>
                        </div>
                    </div>
                `).join('');
            }
        }

        // 更新统计信息
        function updateStats() {
            const totalLinks = linksData.length;
            const totalClicks = linksData.reduce((sum, link) => sum + (parseInt(link.clicks) || 0), 0);

            document.getElementById('total-links').textContent = totalLinks;
            document.getElementById('total-clicks').textContent = totalClicks;
        }

        // 关闭模态框
        function closeModal() {
            document.getElementById('edit-modal').classList.remove('show');
        }

        // 重置表单
        function resetForm() {
            document.getElementById('site-config-form').reset();
        }

        // 重置添加链接表单
        function resetAddLinkForm() {
            document.getElementById('add-link-form').reset();
            document.getElementById('add_link_icon').value = 'fas fa-link';
        }

        // HTML 转义函数
        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        // 键盘快捷键
        document.addEventListener('keydown', function (e) {
            // ESC 键关闭模态框
            if (e.key === 'Escape') {
                // 检查哪个弹窗是打开的并关闭它
                if (document.getElementById('edit-modal').classList.contains('show')) {
                    closeModal();
                } else if (document.getElementById('add-modal').classList.contains('show')) {
                    closeAddModal();
                }
            }
        });

        // 访问概览功能
        let visitData = [];
        let currentPage = 1;
        let pageSize = 10;
        let totalPages = 1;

        // 初始化访问概览数据
        function initVisitOverview() {
            loadVisitData();
            setInterval(updateOnlineVisitors, 30000); // 每30秒更新在线访客数
        }

        // 加载访问数据
        async function loadVisitData() {
            try {
                const timeFilter = document.getElementById('time-filter')?.value || 'today';
                const ipSearch = document.getElementById('ip-search')?.value || '';
                const selectedFile = getFileNameByTimeFilter(timeFilter);
                
                const response = await fetch('api.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        action: 'getVisitRecords',
                        selected_file: selectedFile,
                        ip_search: ipSearch,
                        page: currentPage,
                        page_size: pageSize
                    })
                });

                const result = await response.json();
                if (result.status === 'success') {
                    visitData = result.data.records || [];
                    totalPages = result.data.total_pages || 1;
                    updateVisitStats(result.data.stats);
                    renderVisitTable();
                    updatePagination();
                } else {
                    console.error('加载访问数据失败:', result.message);
                    // 显示空数据
                    visitData = [];
                    updateVisitStats({
                        today_visits: 0,
                        today_visitors: 0,
                        avg_duration: 0,
                        online_visitors: 0
                    });
                    renderVisitTable();
                }
            } catch (error) {
                console.error('加载访问数据出错:', error);
                // 显示空数据
                visitData = [];
                updateVisitStats({
                    today_visits: 0,
                    today_visitors: 0,
                    avg_duration: 0,
                    online_visitors: 0
                });
                renderVisitTable();
            }
        }

        // 更新访问统计
        function updateVisitStats(stats) {
            document.getElementById('today-visits-count').textContent = stats.today_visits || 0;
            document.getElementById('today-visitors-count').textContent = stats.today_visitors || 0;
            document.getElementById('avg-duration').textContent = formatDuration(stats.avg_duration || 0);
            document.getElementById('online-visitors').textContent = stats.online_visitors || 0;
        }

        // 渲染访问记录表格
        function renderVisitTable() {
            const tbody = document.getElementById('visit-records-tbody');
            if (!tbody) return;

            if (visitData.length === 0) {
                tbody.innerHTML = `
                    <tr>
                        <td colspan="8" style="text-align: center; padding: 40px; color: var(--gray-500);">
                            <i class="fas fa-inbox" style="font-size: 24px; margin-bottom: 8px; display: block;"></i>
                            暂无访问记录
                        </td>
                    </tr>
                `;
                return;
            }

            tbody.innerHTML = visitData.map(record => `
                <tr>
                    <td>${formatDateTime(record.visit_time)}</td>
                    <td><span class="ip-address">${record.ip_address}</span></td>
                    <td>
                        <div class="location-info">
                            <span class="location-flag" style="background-image: url('https://flagcdn.com/16x12/${(record.country_code || 'xx').toLowerCase()}.png'); background-size: cover;"></span>
                            ${record.location || '未知'}
                        </div>
                    </td>
                    <td>
                        <span class="duration-badge ${getDurationClass(record.duration)}">
                            ${formatDuration(record.duration)}
                        </span>
                    </td>
                    <td>
                        <div class="device-info">
                            <div class="device-type">${record.device_type || '未知设备'}</div>
                            <div class="device-os">${record.os || '未知系统'}</div>
                        </div>
                    </td>
                    <td>
                        <div class="browser-info">
                            <i class="fab fa-${getBrowserIcon(record.browser)}" style="color: ${getBrowserColor(record.browser)};"></i>
                            ${record.browser || '未知浏览器'}
                        </div>
                    </td>
                    <td>
                        <span class="status-badge ${record.is_online ? 'status-online' : 'status-offline'}">
                            ${record.is_online ? '在线' : '离线'}
                        </span>
                    </td>
                    <td>
                        <button class="btn btn-sm btn-secondary" onclick="viewVisitDetail('${record.id}')">
                            <i class="fas fa-eye"></i>
                            详情
                        </button>
                    </td>
                </tr>
            `).join('');
        }

        // 格式化日期时间
        function formatDateTime(timestamp) {
            const date = new Date(timestamp * 1000);
            return date.toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit'
            });
        }

        // 格式化停留时长
        function formatDuration(seconds) {
            if (seconds < 60) {
                return `${seconds}秒`;
            } else if (seconds < 3600) {
                return `${Math.floor(seconds / 60)}分${seconds % 60}秒`;
            } else {
                const hours = Math.floor(seconds / 3600);
                const minutes = Math.floor((seconds % 3600) / 60);
                return `${hours}时${minutes}分`;
            }
        }

        // 获取停留时长样式类
        function getDurationClass(seconds) {
            if (seconds < 30) return 'duration-short';
            if (seconds < 300) return 'duration-medium';
            return 'duration-long';
        }

        // 获取浏览器图标
        function getBrowserIcon(browser) {
            const browserMap = {
                'Chrome': 'chrome',
                'Firefox': 'firefox',
                'Safari': 'safari',
                'Edge': 'edge',
                'Opera': 'opera',
                'Internet Explorer': 'internet-explorer'
            };
            return browserMap[browser] || 'globe';
        }

        // 获取浏览器颜色
        function getBrowserColor(browser) {
            const colorMap = {
                'Chrome': '#4285f4',
                'Firefox': '#ff7139',
                'Safari': '#1b88ca',
                'Edge': '#0078d4',
                'Opera': '#ff1b2d',
                'Internet Explorer': '#1e88e5'
            };
            return colorMap[browser] || '#6b7280';
        }

        // 筛选访问数据
        function filterVisitData() {
            currentPage = 1;
            loadVisitData();
        }

        // 根据时间筛选获取对应的文件名
        function getFileNameByTimeFilter(timeFilter) {
            const today = new Date();
            let targetDate;
            
            switch (timeFilter) {
                case 'today':
                    targetDate = today;
                    break;
                case 'yesterday':
                    targetDate = new Date(today.getTime() - 24 * 60 * 60 * 1000);
                    break;
                case 'week':
                case 'month':
                default:
                    return 'all'; // 获取所有记录
            }
            
            const year = targetDate.getFullYear();
            const month = String(targetDate.getMonth() + 1).padStart(2, '0');
            const day = String(targetDate.getDate()).padStart(2, '0');
            
            return `${year}-${month}-${day}`;
        }

        // 刷新访问数据
        function refreshVisitData() {
            loadVisitData();
            showMessage('数据已刷新', 'success');
        }

        // 导出访问数据
        function exportVisitData() {
            const timeFilter = document.getElementById('time-filter').value;
            const ipSearch = document.getElementById('ip-search').value;
            
            const params = new URLSearchParams({
                action: 'exportVisitRecords',
                time_filter: timeFilter,
                ip_search: ipSearch
            });
            
            window.open(`api.php?${params.toString()}`, '_blank');
        }

        // 更新分页
        function updatePagination() {
            const totalRecords = visitData.length;
            const startRecord = (currentPage - 1) * pageSize + 1;
            const endRecord = Math.min(currentPage * pageSize, totalRecords);
            
            document.getElementById('page-start').textContent = startRecord;
            document.getElementById('page-end').textContent = endRecord;
            document.getElementById('total-records').textContent = totalRecords;
            
            // 更新分页按钮
            document.getElementById('prev-page').disabled = currentPage <= 1;
            document.getElementById('next-page').disabled = currentPage >= totalPages;
            
            // 生成页码
            const pageNumbers = document.getElementById('page-numbers');
            let pagesHtml = '';
            
            const startPage = Math.max(1, currentPage - 2);
            const endPage = Math.min(totalPages, currentPage + 2);
            
            for (let i = startPage; i <= endPage; i++) {
                pagesHtml += `
                    <span class="page-number ${i === currentPage ? 'active' : ''}" onclick="goToPage(${i})">
                        ${i}
                    </span>
                `;
            }
            
            pageNumbers.innerHTML = pagesHtml;
        }

        // 切换页面
        function changePage(direction) {
            const newPage = currentPage + direction;
            if (newPage >= 1 && newPage <= totalPages) {
                currentPage = newPage;
                loadVisitData();
            }
        }

        // 跳转到指定页面
        function goToPage(page) {
            if (page >= 1 && page <= totalPages) {
                currentPage = page;
                loadVisitData();
            }
        }

        // 查看访问详情
        function viewVisitDetail(recordId) {
            // 这里可以实现访问详情的弹窗或跳转
            showMessage('访问详情功能开发中...', 'info');
        }

        // 更新在线访客数
        async function updateOnlineVisitors() {
            try {
                const response = await fetch('api.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        action: 'getOnlineVisitors'
                    })
                });

                const result = await response.json();
                if (result.status === 'success') {
                    document.getElementById('online-visitors').textContent = result.data.count || 0;
                }
            } catch (error) {
                console.error('更新在线访客数出错:', error);
            }
        }

        // 访问概览初始化现在由switchTab函数统一处理
    </script>

<?php
// 引用footer.php文件
include 'footer.php';
?>